package fightplan.actions;

import java.awt.event.ActionEvent;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import fightplan.persistence.FilePersistence;
import fightplan.views.MainView;

@SuppressWarnings("serial")
public class LoadTournamentAction extends UndoableAction {

	private MainView mainView;

	public LoadTournamentAction(MainView mainView) {
		super("Turnier laden", mainView, "Laden");
		this.mainView = mainView;
	}

	public boolean doAction(ActionEvent actionEvent) {
		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setCurrentDirectory(new File("."));
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		fileChooser.setDialogTitle("Turnier Laden");
		fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
			public boolean accept(File f) {
				return !f.isFile() || f.getName().endsWith(".trn");
			}

			public String getDescription() {
				return "TRN (Turnier) (*.trn)";
			}
		});
		if (fileChooser.showDialog(mainView, "Laden") == JFileChooser.APPROVE_OPTION) {
			try {
				mainView.getTournament().setValue(FilePersistence.load(fileChooser.getSelectedFile(), true));
				return true;
			} catch (Exception x) {
				x.printStackTrace();
				JOptionPane
						.showMessageDialog(mainView,
								"File kann nicht gelesen. Es ist entweder kein Turnierfile\noder von einer anderen Version geschrieben worden.");
				return false;
			}
		} else {
			return false;
		}
	}

}